<?php
/**
 * this class is required because when we move application to scare, use mysql to
 * store site configureation is not effecition as use mongodb or frake database.
 */

class Config implements ArrayAccess
{
	protected $_data = array();

	function __construct($data)
	{
		$this -> _data = $data;
	}

	function offsetGet($key)
	{
		return isset($this -> _data[$key]) ? $data[$key] : NULL;
	}

	function offsetExists($key)
	{
		return isset($this -> _data[$key]);
	}

	function offsetSet($key, $value)
	{
		$this -> _data[$key] = $value;
	}

	function offsetUnset($key)
	{
		if (isset($this -> _data[$key]))
		{
			unset($this -> _data[$key]);
		}
	}

	function __get($key)
	{
		return isset($this -> _data[$key]) ? $this -> _data[$key] : NULL;
	}

	function __set($key, $value)
	{
		$this -> _data[$key] = $value;
	}

	function get($name, $default = NULL)
	{
		return isset($this -> _data[$name]) ? $this -> _data[$name] : $default;
	}

	function set($name, $value)
	{
		$this -> _data[$name] = $value;
		return $this;
	}

	function fromArray($data)
	{
		$this -> _data = $data;
		return $this;
	}

	function toArray()
	{
		return (array)$this -> _data;
	}

	/**
	 * return configure instance
	 * @param  string $name
	 * @return Database_Table Configure Table associate with name
	 */
	static public function instance($name = null)
	{
		static $instances = array();

		if (null == $name)
		{
			$name = 'core/config';
		}

		if (!isset($instances[$name]))
		{
			$instances[$name] = Model::getTable($name);
		}

		return $instances[$name];
	}

	/**
	 * @example Config::readFile('core') will load /config/core.php
	 *
	 * read core configure from hard file, it is required to bootstrap application.
	 * @param string $name file name does not include extension. configure file
	 * extension alway ended by .php
	 * @param array $default value
	 * @return array
	 */
	static public function readFile($file, $name = null, $default = array())
	{
		$data = array();

		if (file_exists($filename = APP_ROOT_PATH . '/config/' . $file . '.php'))
		{
			$data =
			include $filename;
		}
		else
		if (file_exists($filename = SYSTEM_ROOT_PATH . '/config/' . $file . '.php'))
		{
			$data =
			include $filename;
		}
		else
		{
			$data = $default;
		}

		if ($name)
		{
			return isset($data[$name]) ? $data[$name] : $default;
		}

		return $data;
	}

	/**
	 * load file configure
	 * @param string $filename
	 * @param string $name
	 * @return mixed
	 */
	static public function writeFile($file, $data)
	{
		$filename = APP_ROOT_PATH . '/config/' . $file;

		if ($fp = @fopen($fp, 'w'))
		{
			$string = '<?php defined("AGILET") or die("Denied"); return ' . var_export($data, 1) . '; ?>';
			fwrite($fp, $string);
			fclose($fp);
		}
		else
		{
			throw new Agilet_Exception('cound not save {file}.', array('{file}' => $file));
		}
	}

}
